package com.huan.ohc;

import org.caffinitas.ohc.CacheSerializer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * String 类型的值序列化和反序列化
 *
 * @author huan.fu
 * @date 2023/5/16 - 20:41
 */
public class StringCacheSerializer implements CacheSerializer<String> {
    @Override
    public void serialize(String s, ByteBuffer buf) {
        // 得到字符串对象UTF-8编码的字节数组
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        // 用前16位记录数组长度
        buf.put((byte) ((bytes.length >>> 8) & 0xFF));
        buf.put((byte) ((bytes.length) & 0xFF));
        buf.put(bytes);
    }

    @Override
    public String deserialize(ByteBuffer buf) {
        // 获取字节数组的长度
        int length = (((buf.get() & 0xff) << 8) + ((buf.get() & 0xff)));
        byte[] bytes = new byte[length];
        // 读取字节数组
        buf.get(bytes);
        // 返回字符串对象
        return new String(bytes, StandardCharsets.UTF_8);
    }

    @Override
    public int serializedSize(String s) {
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        return bytes.length + 2;
    }
}
